const websocketService = require('../services/wsService');
const GatherDevice = require('../models/gatherDeviceModel'); // 确保路径正确

// 获取所有设备
const getDevices = async (req, res) => {
  try {
    const devices = await GatherDevice.find().lean();

    let deviceInfoList = [];

    for (let i = 0; i < devices.length; i++) {
      const device = devices[i];

      // 创建父级数据
      let parentData = {
        "authorityId": device.deviceName,
        "deviceName": device.deviceName,
        "accountNickName": null,
        "accountId": null,
        "gatherTitleNum": null,
        "commerceAmountAndNum": null,
        "accountType": null,
        "accountStatus": null,
        "checked": 0,
        "parentId": -1
      }
      deviceInfoList.push(parentData);

      // 创建子级数据
      const accounts = device.accounts;
      for (let j = 0; j < accounts.length; j++) {
        const account = accounts[j];
        let childData = {
          "authorityId": 2,
          "deviceName": account.deviceName,
          "accountNickName": account.accountNickName,
          "accountId": account.accountId,
          "gatherTitleNum": account.gatherTitleNum,
          "accountType": account.accountType,
          "accountRemarks": account.accountRemarks,
          "accountStatus": account.accountStatus,
          "checked": 0,
          "parentId": device.deviceName
        }
        deviceInfoList.push(childData);
      }

    }

    res.json({ code: 0, status: 'success', message: '获取设备成功', data: deviceInfoList });
  } catch (error) {
    res.status(500).json({ message: '获取设备失败', error: error.message });
  }
};

// 添加新设备
const addGatherDevice = async (req, res) => {
  const { deviceName, accounts } = req.body; // 从请求体中获取设备名称和账号数组

  try {
    const newDevice = new GatherDevice({ deviceName, accounts }); // 创建新的 GatherDevice 实例
    const savedDevice = await newDevice.save(); // 保存到数据库
    res.status(201).json({ message: '添加设备成功', data: savedDevice });
  } catch (error) {
    let errorMessage = error.message;
    if (error.name === 'MongoError' && error.code === 11000) {
      errorMessage = '已存在相同设备名称';
    }
    res.status(500).json({ message: '添加设备失败', error: errorMessage });
  }
};

// 批量更新设备账号信息
const updateDeviceAccounts = async (req, res) => {
  const { updateDevices } = req.body; // 从请求体中获取设备对象

  if (typeof updateDevices !== 'object' || Object.keys(updateDevices).length === 0) {
    return res.status(400).json({ message: '设备信息不能为空' });
  }

  try {
    const updates = await Promise.all(
      Object.entries(updateDevices).map(async ([deviceName, accounts]) => { // 遍历对象的每个条目
        if (!Array.isArray(accounts)) {
          throw new Error(`账号信息必须为数组: ${deviceName}`);
        }

        const updatedDevice = await GatherDevice.findOneAndUpdate(
          { deviceName }, // 根据设备名称查找设备
          { $set: { accounts } }, // 更新设备中的账号信息
          { new: true } // 返回更新后的设备
        );

        if (!updatedDevice) {
          throw new Error(`设备未找到: ${deviceName}`);
        }

        return updatedDevice; // 返回更新后的设备
      })
    );

    res.json({ message: '更新账号信息成功', data: updates });
  } catch (error) {
    res.status(500).json({ message: '更新账号信息失败', error: error.message });
  }
};

// 更新指定设备下的某个指定账号信息
const updateDeviceAccount = async (req, res) => {

  console.log("updateDeviceAccount11111111111111")
  console.log(req.body)

  const { deviceName, accountData } = req.body; // 获取设备名称、账号ID和要更新的数据

  let accountId = accountData.accountId

  if (!deviceName || !accountId || typeof accountData !== 'object') {
    return res.status(400).json({ message: '设备名称、账号ID和更新数据不能为空' });
  }

  try {
    const updatedDevice = await GatherDevice.findOneAndUpdate(
      { deviceName, 'accounts.accountId': accountId }, // 查找设备名称和指定账号ID
      { $set: { 'accounts.$': accountData } }, // 更新特定账号信息
      { new: true } // 返回更新后的设备
    );

    if (!updatedDevice) {
      console.log('updateDeviceAccount222222222222222222222222222222222222222222222222222222222222222222222222222')
      return res.status(404).json({ message: `未找到设备或账号: ${deviceName}, ID: ${accountId}` });
    }

    res.json({ message: '更新账号信息成功', data: updatedDevice });
  } catch (error) {
    res.status(500).json({ message: '更新账号信息失败', error: error.message });
  }
};

// 批量删除设备
const deleteDevices = async (req, res) => {
  const { deviceNames } = req.body; // 设备名称数组

  if (!Array.isArray(deviceNames) || deviceNames.length === 0) {
    return res.status(400).json({ message: '未选择设备' });
  }

  try {
    const result = await GatherDevice.deleteMany({ deviceName: { $in: deviceNames } });
    res.json({ message: `${result.deletedCount} 个设备已删除` });
  } catch (error) {
    res.status(500).json({ message: '删除设备失败', error: error.message });
  }
};

// 指定账号执行任务
const accountStartTask = async (req, res) => {
  const { parentId, accountInfo, taskParams } = req.body; // 设备名称数组

  try {

    let message = {
      type: 'accountStartGatherTask',
      data: {
        "parentId": parentId,
        "accountInfo": accountInfo,
        "taskParams": taskParams
      }
    }

    websocketService.sendMessage(parentId, message);

    res.json({ message: '执行任务成功' });
  } catch (error) {
    res.status(500).json({ message: '执行任务失败', error: error.message });
  }

};

// 指定账号停止任务
const accountStopTask = async (req, res) => {
  const { parentId, accountInfo } = req.body; // 设备名称数组

  try {

    let message = {
      type: 'accountStopGatherTask',
      data: accountInfo
    }

    websocketService.sendMessage(parentId, message);

    res.json({ message: '执行任务成功' });
  } catch (error) {
    res.status(500).json({ message: '执行任务失败', error: error.message });
  }

}

module.exports = {
  getDevices,
  addGatherDevice,
  updateDeviceAccount,
  updateDeviceAccounts,
  deleteDevices,
  accountStartTask,
  accountStopTask
};
